package com.mvc.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.util.JSONBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.iconsys.util.EncryptUtils;
import com.mvc.entity.Icon_User;
import com.mvc.service.UserService;

@Controller
public class AdminController {
  protected final transient Log log = LogFactory.getLog(AdminController.class);

  @Autowired
  private UserService userService;

  public AdminController() {

  }

  @RequestMapping(value = "admin/list.page", method = RequestMethod.GET)
  public String listPage(ModelMap modelMap) {
    List<Icon_User> list = userService.findAll();
    modelMap.put("list", list);
    return "user";
  }

  @RequestMapping(value = "admin/login.page", method = RequestMethod.GET)
  public String loginPage(HttpServletRequest request, ModelMap modelMap) throws Exception {
    return "admin/login";
  }

  @RequestMapping(value = "admin/login.do", method = RequestMethod.POST)
  public String login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
    String sessionId = request.getSession().getId();
    Icon_User user = (Icon_User)request.getAttribute("user");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String[] remember = request.getParameterValues("remember");
    
    if (user!=null&&username==null&&password==null) {
      String userSessionId = userService.findSessionIdByUsername(user.getUsername());
      if (userSessionId != null) {
        if (userSessionId.equals(sessionId)) {
          return "admin/index";
        }
      }
    }else if(username!=null&&password!=null){
      Icon_User dbUser = userService.findUserByUsername(username);
      String encryptedStr=EncryptUtils.encryptMD5(password);
      if (dbUser.getPassword().equalsIgnoreCase(encryptedStr)) {
        dbUser.setSessionId(sessionId);
        userService.save(dbUser);
        if(remember!=null&&remember[0].equals("on")){
          Cookie cookie = new Cookie("remenber", "encryptedStr:"+encryptedStr+"sessionId:"+sessionId);
          cookie.setMaxAge(24*3600);
          response.addCookie(cookie);
        }
        return "admin/index";
      }else{
        modelMap.put("loginstatus", "用户名密码错误");
      }
    }
    return "admin/login";
  }
  @RequestMapping(value = "admin/login_cookies.do", method = RequestMethod.POST)
  public String login_cookies(HttpServletRequest request, HttpServletResponse response) throws Exception {
    InputStream is = request.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    String json = br.readLine();
    br.close();
    is.close();
    System.out.println(json);
    String encryptedStr = json.substring(13,45);
    String sessionId = json.substring(55,json.length());
    System.out.println(encryptedStr+"  "+sessionId);
    
    PrintWriter out=response.getWriter();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("SUCCESS", true);
    JSONArray jarr = JSONArray.fromObject(map);
    out.print(jarr.toString());
    out.close();
    return null;
  }

  @RequestMapping(value = "admin/regist.page", method = RequestMethod.GET)
  public String registPage(HttpServletRequest request, ModelMap modelMap) throws Exception {
    return "admin/regist";
  }

  @RequestMapping(value = "admin/regist.do", method = RequestMethod.POST)
  public String register(HttpServletRequest request, ModelMap modelMap) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String repeat = request.getParameter("repeat");
    if (repeat.equals(password)) {
      // 检查用户名是否被占用
      Icon_User tempuser = userService.findUserByUsername(username);
      if (tempuser == null||tempuser.getId()==null) {
        // 验证用户名未被占用
        Icon_User user = new Icon_User();
        user.setUsername(username);
        String encryptStr = EncryptUtils.encryptMD5(password);
        user.setPassword(encryptStr);
        user.setAuthority(1);
        user.setRegisterDate(new Timestamp(new Date().getTime()));
        try {
          userService.save(user);
          modelMap.put("addstate", "注册成功");
          return "admin/login";
        } catch (Exception e) {
          e.printStackTrace();
          log.error(e.getMessage());
          modelMap.put("addstate", "注册失败");
        }
      }else{//用户名是否被占用
        modelMap.put("addstate", "用户名已被占用");
      }
    }else{
      modelMap.put("addstate", "两次输入的密码不一致");
    }
    return "admin/regist";
  }

  @RequestMapping(value = "/delUser.do", method = RequestMethod.GET)
  public void delUser(@RequestParam("id") String id, HttpServletResponse response) {
    try {
      Long uid = Long.parseLong(id);
      Icon_User user = userService.find(uid);
      userService.delete(user);
      response.getWriter().print("{\"SUCCESS\":\"true\"}");
    } catch (Exception e) {
      log.error(e.getMessage());
      e.printStackTrace();
    }
  }
}
